from django_site2 import settings
from user.models import CustomUser
from django.db import models
from django.shortcuts import reverse
from ckeditor.fields import RichTextField
# Create your models here.


class Category(models.Model):
    title = models.CharField(verbose_name="分类名", max_length=100, unique=True)
    parent = models.ForeignKey(verbose_name="父级分类", to="Category",  on_delete=models.CASCADE, blank=True, null=True)

    def children(self):
        return Category.objects.filter(parent=self)

    def __str__(self):
        return self.title


class Tag(models.Model):
    title = models.CharField(verbose_name="标签名", max_length=100, unique=True)

    def __str__(self):
        return self.title


class Article(models.Model):
    title = models.CharField(verbose_name="标题", max_length=100)
    content = RichTextField(verbose_name="正文")
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    categorys = models.ManyToManyField(verbose_name="所属分类", to=Category)
    tags = models.ManyToManyField(verbose_name="所有标签", to=Tag)
    author = models.ForeignKey(verbose_name="作者", to=CustomUser, on_delete=models.CASCADE)
    state = models.CharField(verbose_name="审核状态", max_length=10, choices=(
        ('success', "已通过"),
        ('fail', '已驳回'),
        ('undo', '未处理')
    ), default='undo')

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('main:article_detail', kwargs={'pk': self.pk})

    class Meta:
        ordering = ['-create_time']


class BrowseHistory(models.Model):
    """用户浏览历史记录模型"""
    user = models.ForeignKey(verbose_name="用户", to=CustomUser, on_delete=models.CASCADE)
    article = models.ForeignKey(verbose_name="浏览的文章", to='Article', on_delete=models.CASCADE)
    browse_time = models.DateTimeField(verbose_name="浏览时间", auto_now_add=True)
    is_deleted = models.BooleanField(verbose_name="是否已删除", default=False)
    
    class Meta:
        verbose_name = "浏览历史"
        verbose_name_plural = "浏览历史"
        ordering = ['-browse_time']
        # 移除unique_together约束，允许记录每次浏览以统计真实浏览次数
    
    def __str__(self):
        return f"{self.user.username} 浏览了 {self.article.title} ({self.browse_time})"
